<template>
  <!-- 批量打印架签 -->
  <div class="container">
    <el-row :gutter="20">
      <el-col :span="4">
        <el-card class="postion-tree">
          <el-tree ref="treeRef" node-key="id" :data="colTree" :props="defaultProps" :highlight-current="true"
            @node-click="handleNodeClick">
            <span slot-scope="{ node }" style="font-size: 14px">
              <i v-if="node.level == 1" class="iconfont icon-shouye"></i>
              <i v-else-if="node.level == 2" class="iconfont icon-wenjianguanli"></i>
              <i v-else class="iconfont icon-0-52"></i>
              <span style="margin-left: 10px">{{ node.label }}</span>
            </span>
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="20" style="padding-left: 0">
        <el-card class="box-card" :body-style="{ padding: '10px 10px 2px 10px' }">
          <el-form :inline="true" :model="queryParam" class="demo-form-inline" size="medium">
            <el-form-item label="库位名称">
              <el-input v-model="queryParam.positionName" placeholder="请输入库位名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="RFID">
              <el-input v-model="queryParam.rfid" placeholder="请输入RFID" clearable></el-input>
            </el-form-item>
            <el-form-item label="是否已发标签">
              <el-select v-model="queryParam.rfidFlag" placeholder="请选择" clearable>
                <el-option v-for="item in [
                  { value: 0, label: '是' },
                  { value: 1, label: '否' },
                ]" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit">查询</el-button>
              <el-button @click="rest">重置</el-button>
            </el-form-item>
            <el-form-item style="margin-bottom: 0">
              <el-button type="primary" icon="el-icon-download" @click="exportExcel">导出</el-button>
            </el-form-item>
            <el-form-item style="margin-bottom: 0">
              <el-button type="primary" icon="el-icon-download" @click="downloadTemplate">下载模板</el-button>
            </el-form-item>
            <el-form-item style="margin-bottom: 0">
              <el-tooltip content="先下载导入模板，使用模板进行导入" placement="top" effect="light">
                <el-button type="primary" icon="el-icon-upload2" @click="importExcel">导入</el-button>
              </el-tooltip>
            </el-form-item>
            <!-- <el-form-item style="margin-bottom: 0">
              <el-button type="primary" icon="el-icon-plus" @click="sendTags">发标签</el-button>
            </el-form-item> -->
            <el-form-item style="margin-bottom: 0">
              <el-tooltip content="RFID实体标签更换，RFID号不变" placement="top" effect="light">
                <el-button type="primary" @click="handleReplace">批量更换标签</el-button>
              </el-tooltip>
            </el-form-item>
            <el-form-item style="margin-bottom: 0">
              <el-tooltip content="RFID实体标签更换，RFID号重新注册" placement="top" effect="light">
                <el-button type="primary" @click="batchRegister">批量注册标签</el-button>
              </el-tooltip>
            </el-form-item>
            <el-form-item>
              <el-tooltip content="RFID号取消绑定:将RFID号在系统中去除" placement="top" effect="light">
                <el-button type="primary" @click="unbindRfid">取消绑定标签</el-button>
              </el-tooltip>
            </el-form-item>
          </el-form>
          <input ref="excelUploadInput" type="file" accept=".xlsx, .xls" style="display: none" @change="uploadChange" />
        </el-card>
        <el-card class="box-card" :body-style="{ padding: 10 }">
          <el-table :data="tableData" border style="width: 100%" height="54vh" ref="table"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" sortable> </el-table-column>
            <el-table-column v-for="item of tableProps" :key="item.props" :prop="item.prop" :label="item.title"
              :width="item.width" :show-overflow-tooltip="true">
              <template #default="scope">
                <span v-if="item.prop === 'stageStatus'">
                  <el-tag v-show="scope.row.stageStatus == 0">未上架</el-tag>
                  <el-tag v-show="scope.row.stageStatus == 1" type="success">已上架</el-tag>
                  <el-tag v-show="scope.row.stageStatus == 2" type="danger">已下架</el-tag>
                </span>
                <span v-else-if="item.prop === 'storeStatus'">
                  <el-tag v-show="scope.row.storeStatus == 0">未入库</el-tag>
                  <el-tag v-show="scope.row.storeStatus == 1" type="success">在库</el-tag>
                  <el-tag v-show="scope.row.storeStatus == 2" type="danger">离库</el-tag>
                </span>
                <span v-else>{{ scope.row[item.prop] }}</span>
              </template>
            </el-table-column>
            <!--            <el-table-column label="操作" min-width="150">-->
            <!--              <template slot-scope="{ row }">-->
            <!--                <el-button link size="mini" @click="replaceLabel(row)">更换标签</el-button>-->
            <!--                <el-button link size="mini" style="color: #67c23a" @click="reRegister(row)"-->
            <!--                >重新注册</el-button-->
            <!--                >-->
            <!--              </template>-->
            <!--            </el-table-column>-->
          </el-table>
        </el-card>
        <el-card class="box-card" :body-style="{ padding: 10 }">
          <pagination ref="pagination" :totalCount="totalCount" @pagination="pagination"></pagination>
        </el-card>
      </el-col>
    </el-row>
    <label-replace-dialog ref="labelReplaceDialog" @ok="loadData"></label-replace-dialog>
    <send-tags-dialog ref="sendTagsDialog" @ok="loadData"></send-tags-dialog>
    <label-batch-replace-dialog ref="labelBatchReplaceDialog" @ok="loadData"
      :field="field"></label-batch-replace-dialog>
  </div>
</template>

<script>
import {
  downloadTemplate,
  importData,
  rfidCabinetPositionpage,
  unbindRfid,
} from '@/api/rfid/position'
import { queryShelfTemp } from '@/api/sys/template'
import { queryColTree } from '@/api/bas/cabinet'
import { exportExcel } from '@/api/rfid/position'
import labelReplaceDialog from './dialog/labelReplaceDialog.vue'
import sendTagsDialog from './dialog/sendTagsDialog.vue'
import labelBatchReplaceDialog from './dialog/labelBatchReplaceDialog.vue'
export default {
  name: 'archiveLabelReplace',
  components: { labelReplaceDialog, sendTagsDialog, labelBatchReplaceDialog },
  data() {
    return {
      totalCount: 0, //总数
      //查询条件
      searchModel: {
        pageNo: 1,
        pageSize: 10,
      },
      queryParam: {},
      tableData: [],
      tableProps: [
        { title: '库位名称', prop: 'positionName', width: '', checked: true },
        { title: '库位编号', prop: 'positionId', width: '', checked: true },
        { title: 'RFID', prop: 'rfid', width: '', checked: true },
        { title: '库房名称', prop: 'repositoryName', width: '', checked: true },
        { title: '装具名称', prop: 'cabinetName', width: '', checked: true },
        { title: '列名称', prop: 'colName', width: '', checked: true },
      ],
      selectionData: [],
      colTree: [],
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      currentNode: null,
      field: {},
    }
  },
  mounted() {
    this.getColTree()
    this.loadData()
  },
  methods: {
    getColTree() {
      queryColTree({})
        .then((res) => {
          if (res.data.code === 200) {
            // 将res.data.data转为数组
            this.colTree = res.data.data
          } else {
            this.$message.warning(res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },
    handleNodeClick(data, node) {
      if (this.currentNode && this.currentNode.id === data.id) {
        node.checked = !node.checked
      } else {
        node.checked = true
      }

      // if (node.checked) {
      // bug 去掉取消不去调用分页
      // 选中
      this.currentNode = data
      // 点击库房
      if (node.level === 1) {
        this.queryParam.deviceId = null
        this.queryParam.colId = null
        this.queryParam.repositoryId = data.id
        this.loadData()
      } else if (node.level === 2) {
        this.queryParam.repositoryId = null
        this.queryParam.colId = null
        this.queryParam.deviceId = data.id
        this.loadData()
      } else if (node.level === 3) {
        this.queryParam.repositoryId = null
        this.queryParam.deviceId = null
        this.queryParam.colId = data.id
        this.loadData()
      }
      // } else {
      //   // 取消选中
      //   this.$refs.treeRef.setCurrentKey(null)
      //   this.currentNode = null
      //   this.queryParam.repositoryId = null
      //   this.queryParam.deviceId = null
      //   this.queryParam.colId = null
      //   this.loadData()
      // }
    },
    onSubmit() {
      this.$refs.pagination.resetPagination()
    },
    rest() {
      this.queryParam = {}
      this.$refs.pagination.resetPagination()
    },
    handleReplace() {
      if (this.selectionData.length === 0) {
        this.$message.warning('请选择要更换标签的层架')
        return
      }
      // 如果rfid为空，不允许
      if (this.selectionData.some((item) => item.rfid === null)) {
        this.$message.warning('请选择已注册rfid的层架')
        return
      }
      this.$refs.labelBatchReplaceDialog.add(this.selectionData, 'replace', 'shelf')
      this.getTemplateTableProps()
    },
    batchRegister() {
      if (this.selectionData.length === 0) {
        this.$message.warning('请选择要重新注册的层架')
        return
      }
      // // 如果rfid为空，不允许
      // if (this.selectionData.some((item) => item.rfid === null)) {
      //   this.$message.warning('请选择已注册rfid的层架')
      //   return
      // }
      this.$refs.labelBatchReplaceDialog.add(this.selectionData, 'register', 'shelf')
      this.getTemplateTableProps()
    },
    // 取消绑定
    unbindRfid() {
      if (this.selectionData.length === 0) {
        this.$message.warning('请选择要取消绑定标签的库位')
        return
      }
      // 选择的档案盒rfid不为为空
      if (this.selectionData.some((item) => item.rfid === null || item.rfid === '')) {
        this.$message.warning('存在未注册rfid的库位')
        return
      }
      this.$confirm('此操作将会在系统中去除当前的RFID号，请谨慎操作, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          let positionIds = this.selectionData.map((item) => item.positionId)
          unbindRfid(positionIds).then((res) => {
            if (res.data.code === 200) {
              this.$message.success('取消绑定成功')
              this.loadData()
            } else {
              this.$message.error(res.data.message)
            }
          })
        })
        .catch((error) => {
          if (error !== 'cancel') {
            // 其他错误情况，例如网络错误等
            this.$message.error(error)
          }
        })
    },
    // 获取模版需要打印的字段
    getTemplateTableProps() {
      queryShelfTemp().then((res) => {
        if (res.data.code == 200) {
          this.field = res.data.data
        }
      })
    },
    handleSelectionChange(val) {
      this.selectionData = val
    },
    loadData() {
      const param = Object.assign(this.queryParam, this.searchModel)
      rfidCabinetPositionpage(param)
        .then((res) => {
          if (res.data.code === 200) {
            this.tableData = res.data.data.records
            this.totalCount = res.data.data.total
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    pagination(val) {
      this.searchModel.pageNo = val.page
      this.searchModel.pageSize = val.limit
      this.loadData()
    },
    exportExcel() {
      exportExcel(this.queryParam)
        .then((res) => {
          // 创建一个新的URL代表指定的File对象或Blob对象
          const url = window.URL.createObjectURL(new Blob([res.data]))
          // 创建一个a标签用于下载
          const link = document.createElement('a')
          link.href = url
          link.setAttribute('download', '库位数据.xlsx') // 下载文件名
          document.body.appendChild(link)
          link.click()
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    downloadTemplate() {
      downloadTemplate()
        .then((res) => {
          // 创建一个新的URL代表指定的File对象或Blob对象
          const url = window.URL.createObjectURL(new Blob([res.data]))
          // 创建一个a标签用于下载
          const link = document.createElement('a')
          link.href = url
          link.setAttribute('download', '层架标签导入模板.xlsx') // 下载文件名
          document.body.appendChild(link)
          link.click()
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    importExcel() {
      // 先选择左侧树装具
      if (this.queryParam.deviceId === null || this.queryParam.deviceId === undefined) {
        this.$message.warning('请选择左侧装具')
        return
      }
      this.$refs.excelUploadInput.click()
    },
    async uploadChange(event) {
      const files = event.target.files
      if (files.length > 0) {
        // 大于0，说明有文件要上传
        // 创建FormData对象
        const data = new FormData()
        // 添加文件
        data.append('file', files[0])
        data.append('deviceId', this.queryParam.deviceId)
        // 调用接口
        await importData(data)
          .then((res) => {
            if (res.data.code === 200) {
              this.$message.success('导入成功！')
              this.loadData()
            } else {
              this.$message.error(res.data.message)
            }
          })
          .catch((err) => {
            this.$message.error(err)
          })
          .finally(() => {
            this.$refs.excelUploadInput.value = ''
          })
      }
    },
    // 发标签
    sendTags() {
      if (this.selectionData.length === 0) {
        this.$message.warning('请选择要发标签的层架')
        return
      }
      // 如果勾选的数据存在rfid
      if (this.selectionData.some((item) => item.rfid)) {
        this.$message.warning('已选择层架中存在已发标签的层架，请重新选择')
        return
      }
      this.$refs.sendTagsDialog.add(this.selectionData, 'shelf')
    },
  },
}
</script>

<style lang="less" scoped>
.container {
  height: 90%;

  .el-row {
    height: 100%;

    .el-col {
      height: 100%;

      .postion-tree {
        height: 75vh;
      }
    }
  }
}
</style>
